package com.alison.module.authors.mapper;

import com.alison.module.authors.domain.param.UserParam;
import com.alison.module.authors.entity.User;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class UserSql {

    private static final Logger log = LoggerFactory.getLogger(UserSql.class);

    public String getList(UserParam userParam) {
        StringBuffer sql = new StringBuffer("select id, user_name as userName, pass_word as passWord, user_sex as userSex, nick_name as nickName");
        sql.append(" from user where 1=1 ");
        if (userParam != null) {
            if (!StringUtils.isEmpty(userParam.getUserName())) {
                sql.append(" and userName = #{userName}");
            }
            if (!StringUtils.isEmpty(userParam.getUserSex())) {
                sql.append(" and userSex = #{userSex}");
            }
        }
        sql.append(" order by id desc");
        sql.append(" limit " + userParam.getOffset() + "," + userParam.getPageSize());
        log.info("getList sql is :" + sql);
        return sql.toString();
    }

    public String getCount(UserParam userParam) {
        String sql = new SQL() {{
            SELECT("count(1)");
            FROM("user");
            if (!StringUtils.isEmpty(userParam.getUserName())) {
                WHERE("user_name = #{userName}");
            }
            if (!StringUtils.isEmpty(userParam.getUserSex())) {
                WHERE("user_sex = #{userSex}");
            }
            //从这个toString可以看出，其内部使用高效的StringBuilder实现SQL拼接
        }}.toString();

        log.info("getCount sql is :" + sql);
        return sql;
    }

    public String update(User user) {
        String sql = new SQL() {{
            UPDATE("user");
            if (!StringUtils.isEmpty(user.getNickName())) {
                SET("nick_name=#{nickName}");
            }
            if (!StringUtils.isEmpty(user.getUserName())) {
                SET("user_name=#{userName}");
            }
            if (!StringUtils.isEmpty(user.getPassWord())) {
                SET("pass_word=#{passWord}");
            }
            if (!StringUtils.isEmpty(user.getUserSex())) {
                SET("user_sex=#{userSex}");
            }
            WHERE("id=#{id}");
        }}.toString();
        return sql;
    }
}

